package com.cat.gridChart;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/YesdPw/description/
 * @create 2025/9/6 20:15
 * @since JDK17
 */

public class Solution04 {
    int n, m, ans;
    boolean[][] vis;
    int[][] d = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    boolean judge(int i, int j) {
        return i == -1 || j == -1 || i == n || j == m;
    }

    int dfs(String[] grid, int i, int j, char target) {
        if (judge(i, j) || vis[i][j] || grid[i].charAt(j) != target) {
            return 0;
        }
        vis[i][j] = true;
        int ans = 1;
        for (int k = 0; k < 4; k++) {   // 继续往下递归
            ans += dfs(grid, i + d[k][0], j + d[k][1], target);
        }
        return ans;
    }


    public int largestArea(String[] grid) {
        n = grid.length;
        m = grid[0].length();
        vis = new boolean[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i].charAt(j) == '0' ) {
                    vis[i][j] = true;
                    for (int k = 0; k < 4; k++) {
                        int ni = i + d[k][0], nj = j + d[k][1];
                        if (!judge(ni, nj) && grid[ni].charAt(nj) != '0') {
                            dfs(grid, ni, nj, grid[ni].charAt(nj));
                        }
                    }
                }
                if (i == 0 || i == n - 1 || j == 0 || j == m - 1) {
                    dfs(grid, i, j, grid[i].charAt(j));
                }
            }
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (!vis[i][j] && grid[i].charAt(j) != '0') {
                    ans = Math.max(ans, dfs(grid, i, j, grid[i].charAt(j)));
                }
            }
        }
        return ans;
    }
}
